<template>
  <div class="categories">
    <base-template :breadList="['商品管理', '商品列表']">
      <el-row>
        <el-button type="primary" @click="addItem">添加分类</el-button>
      </el-row>

      <el-table :data="categoriesData" border stripe row-key="cat_id" :tree-props="tableProps">
        <!-- <el-table-column label="#" type="index" width="50"> </el-table-column> -->
        <el-table-column prop="cat_name" label="分类名称"> </el-table-column>
        <el-table-column prop="date" label="是否有效" width="100">
          <template v-slot="scope">
            <i v-if="scope.row.cat_delete" class="el-icon-error"></i>
            <i class="el-icon-success"></i>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="排序" width="100">
          <template v-slot="scope">
            <el-tag effect="dark" size="mini" v-if="scope.row.cat_level == 0">一级</el-tag>
            <el-tag effect="dark" size="mini" type="success" v-else-if="scope.row.cat_level == 1">二级</el-tag>
            <el-tag type="danger" size="mini" effect="dark" v-else>三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="scope">
            <el-button size="mini" type="primary" class="marginRight" @click="editItem(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="removeItem(scope.row)">
              <el-button type="danger" size="mini" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationInfo.pagenum"
        :page-sizes="[2, 5, 10, 50]"
        :page-size="paginationInfo.pagesize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </base-template>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="ruleForm.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" v-if="dialogTitle == '添加分类'">
          <el-cascader v-model="selectCascader" style="width: 100%" :options="options" :props="props"></el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BaseTemplate from '../../component/base-template.vue'
export default {
  components: {
    BaseTemplate,
  },
  data() {
    return {
      categoriesData: [],
      tableProps: {
        children: 'children',
      },
      paginationInfo: {
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      tempId: '',

      dialogVisible: false,
      ruleForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      rules: {
        cat_name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }],
      },
      options: [], //级联数据
      selectCascader: [],
      props: {
        //配置
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id',
      },
      dialogTitle: '添加分类',
    }
  },
  created() {
    this.getCategoriesData()
  },
  methods: {
    async getCategoriesData() {
      const { total, result } = await this.$store.dispatch('getRequest', { path: '/categories', params: this.paginationInfo })

      this.total = total
      this.categoriesData = result
    },
    handleSizeChange(val) {
      this.paginationInfo.pagesize = val
      this.getCategoriesData()
    },
    handleCurrentChange(val) {
      this.paginationInfo.pagenum = val
      this.getCategoriesData()
    },
    async addItem() {
      this.dialogVisible = true
      this.dialogTitle = '添加分类'
      const res = await this.$store.dispatch('getRequest', { path: '/categories' ,params:{type:[2]}})
      this.options = res
    },
    editItem(row) {
		this.tempId=''
      this.dialogVisible = true
      this.dialogTitle = ''
	  this.ruleForm.cat_name=row.cat_name
	  this.tempId=row.cat_id
    },
    async removeItem(row) {
      const meta = await this.$store.dispatch('deleteRequest', { path: `/categories/${row.cat_id}` })
      if (meta.status == 200) {
        this.$message.success('成功删除')
        this.getCategoriesData()
      } else {
        this.$message.error('删除失败')
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.clearStatus()

          done()
        })
        .catch((_) => {})
    },
    submitEdit() {
      this.ruleForm.cat_level = this.selectCascader.length
      if (this.selectCascader.length == 0) {
        this.ruleForm.cat_pid = 0
      } else {
        this.ruleForm.cat_pid = this.selectCascader.slice(-1)
      }

      this.$refs.ruleForm.validateField(['cat_name'], async (valid) => {
        if (!valid) {
          if (this.dialogTitle == '添加分类') {
            const res = await this.$store.dispatch('postRequest', { path: '/categories', params: this.ruleForm })

            if (res.meta.status == 201) {
              this.$message.success('添加成功')
              this.getCategoriesData()
            } else {
              this.$message.error('添加失败')
            }
            this.clearStatus()
          }else{
			  const {meta,data}=await this.$store.dispatch('putRequest',{path:`/categories/${this.tempId}`,params:{cat_name:this.ruleForm.cat_name}})
			if(meta.status==200){
				this.getCategoriesData()
				this.$message.success('更新成功')

			}else{
				this.$message.error('更新失败')
			}
			this.clearStatus()
		  }
        }
      })
    },
    clearStatus() {
      this.$refs.ruleForm.resetFields()

      this.dialogTitle = ''
      this.selectCascader = []
      this.dialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
i.el-icon-error {
  color: #f00;
}
i.el-icon-success {
  color: #0f0;
}
</style>
